<template>
  <div class="multi_selected">
    <el-tooltip v-for="(item) in selectionList"
                :key="item[keyName]"
                :content="item[keyShow]"
                :disabled="item[keyShow]?.length < 10"
                placement="top">
      <el-tag style="margin: 0.2rem;"
              closable
              :disable-transitions="false"
              @close="handleClose(item)">
        <div style="overflow: hidden;text-overflow: ellipsis;white-space: nowrap;max-width: 4rem;display: inline-block;">
          {{ item[keyShow] }}
        </div>
      </el-tag>
    </el-tooltip>
  </div>
  <el-table ref="tab" :data="list"
            :row-key="keyName"
            @select="handleSelect"
            @select-all="handleSelectAll"
            border
            :max-height="maxHeight"
            :key="2">
    <el-table-column type="selection" width="39px"/>
    <slot name="tableColumn"></slot>
  </el-table>
</template>

<script>
export default {
  name: "MultiplePageSelectionTable",
  emits: ['update:modelValue', 'onchange'],
  props: {
    keyName: {
      type: String,
      required: true,
    },
    keyShow: {
      type: String,
      required: true,
    },
    isExist: Function,
    maxHeight: String,
  },
  data() {
    return {
      list: [],
      selectionList: []
    }
  },
  watch: {
    selectionList() {
      this.$emit('onchange', this.selectionList)
    }
  },
  methods: {
    handleClose(item) {
      this.selectionList = this.selectionList.filter(n => n[this.keyName] !== item[this.keyName])
      this.$emit('update:modelValue', this.selectionList.join(','))
      this.$emit('onchange', this.selectionList)
    },
    initSelect(selectionList = []) {
      this.selectionList = selectionList
    },
    setList(list) {
      this.list = list
      // this.$refs.tab.doLayout()
      this.$nextTick(() => {
        if (this.selectionList?.length > 0) {
          this.list.map(row => {
            let idx = this.selectionList.findIndex(item => this.isExist(row, item))
            if (idx !== -1) {
              this.$refs.tab.toggleRowSelection(row, true)
              this.selectionList.splice(idx, 1, row)
            }
          })
          this.$emit('onchange', this.selectionList)
        }
      })
    },
    handleSelect(data) {
      this.setSelectionList(data)
    },
    handleSelectAll(data) {
      this.setSelectionList(data)
    },
    setSelectionList(data) {
      //删除在选择list中，当前表格中存在的数据；防止数据跟新，要在选择list中存放最新的数据
      this.selectionList = this.selectionList.filter(selItem => {
        return !this.list.find(listItem => this.isExist(listItem, selItem));
      })
      this.selectionList = [...this.selectionList, ...data]
      console.debug('selectionList',this.selectionList)
    }
  }
}
</script>
<style>
.multi_selected {
  border: 1px solid #ccc;
  border-radius: 5px;
  min-height: 33px;
  height: auto;
  margin: 5px 0;
}
</style>
